<?php

  class BPlugin_cookie extends BPlugin
  {

      private $_cookie_path = '/';

      /**
       * 设置COOKIE
       *
       * @access public
       * @param string $var
       * @param string $val
       * @param int    $expire
       */
      function set($var, $val = null, $expire = 0, $domain = null)
      {
          @setcookie($var, $val, $this->time->time(true) + $expire, $this->_cookie_path, HOST_DOMAIN);
          return true;
      }

      function get($var)
      {
          if (is_null($var)) {
              return $_COOKIE;
          } else {
              return $_COOKIE[$var];
          }
      }

      /**
       * 
       * 将限定个数的字符串用逗号分割以字串的形式写入COOKIE中
       *
       * @access public
       * @param $cookiename    存入的COOKIE名
       * @param $nums          记录的条数
       * @param $expire        过期时间    默认为30天
       */
      public function stringsToCookie($id, $cookiename='bookyouviews', $nums = 5, $expire = 2592000)
      {
          $goodidstr = $this->get($cookiename);
          if ($goodidstr) {
              $goodidarr = explode(',', $goodidstr);
              if (!in_array($id, $goodidarr)) {
                  if ($nums == count($goodidarr)) {
                      array_shift($goodidarr);
                  }
                  array_push($goodidarr, $id);
              }

              $goodidstr_new = implode(',', $goodidarr);
          } else {
              $goodidstr_new = $id;
          }

          $this->set($cookiename, $goodidstr_new, $expire);
      }
      
      /**
       *
       * 在cookie保存的逗号分割的字符串返回限定个数
       * 
       * @param type $cookiename    要取的COOKIE名
       * @param type $nums          要返回的数量
       * @return type $except       排除的元素
       */
      public function getStirngsFromCookie($cookiename, $nums = 5, $except = array())
      {
          $str = $this->get($cookiename);
          $strarr = explode(',', $str);
          $strarr = array_diff($strarr, $except);
          if(count($strarr > $nums))
          {
              for($i=0,$j=count($strarr) - $nums;$i<$j; $i++)
              {
                  array_shift($strarr);
              }
          }
          return empty($strarr) ? '' : implode(',', $strarr);
      }

  }